import $http from '@/services/HttpClient'

function coverErrorMsg(resp) {
  if (!resp.data.success) {
    resp.data.error = decodeURI(resp.data.error)
  }
  return resp;
}

/**
 *
 * @param table
 * @param option
 * @returns `{list,params, success, total}`
 * @example getAll: select(tableName)
 * @example page: select(tableName,{page:2,length:10})
 * @example specifyColumns: select(tableName,{page:2,length:10,columns:"name, title"})
 */
export function select(table, option = {}) {
  return $http.get(`/sync/${table}`, { params: { query: JSON.stringify(option) } }).then(coverErrorMsg)
}

/**
 *
 * @param table
 * @param data
 * @returns `[error,data:{list,params, success, total}]`
 * @example insert(tableName,{a:2,b:10,c:"name, title:'titlename'"})
 * @example insert(tableName,[{a:1,b:10,c:"name, title:'titlename'"},{a:2,b:10,c:"name, title:'titlename'"}])
 */
export function insert(table, data = {}) {
  let _data_ = data;
  if (Array.isArray(data)) {
    _data_ = { datas: data.map(d => JSON.stringify(d)).join(',') }
  }
  return $http.post(`/sync/${table}`, _data_).then(coverErrorMsg)
}

/**
 *
 * @param table
 * @param query
 * @param data
 * @returns `[error,data:{list,params, success, total}]`
 * @example update(tablenem, id, {field01:'xxx',field2:'xxxxx'});
 * @example update(tablenem, {id}, {field01:'xxx',field2:'xxxxx'});
 */
export function update(table, query = {}, data = {}) {
  return $http.put(`/sync/${table}`, data, {
    params: { query: JSON.stringify(query) },
  }).then(coverErrorMsg);
};

/**
 *
 * @param table
 * @param query
 * @returns `[error,data:{list,params,success,total}]`
 */
export function remove(table, query = {}) {
  return $http.delete(`/sync/${table}`, {
    params: { query: JSON.stringify(query) },
  }).then(coverErrorMsg);
};

/**
 *
 * @param table
 * @param query
 * @example await dbFetch.count(Table.alert,{user_id:1, is_read:0});
 * @returns `[error,count]`
 */
// export function count(table, query = {}) {
//   $http.post(`/count/${table}`, { params: { query: JSON.stringify(query) } }).then(coverErrorMsg)
// }